package com.killer.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.killer.dao.BOrderDao;
import com.killer.pojo.entity.BOrder;
import com.killer.pojo.entity.Message;
import com.killer.service.BOrderService;
import com.killer.service.FileService;
import com.killer.task.ExportTask;
import com.killer.untils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Service
public class FileServiceImpl implements FileService {


    @Autowired
    private BOrderDao bOrderDao;


    @Override
    public void export(Message message) {
        // 获取可用的线程数
        final int nThreads = Runtime.getRuntime().availableProcessors();
        // io密集型  自定义线程池
        ExecutorService pool = Executors.newFixedThreadPool(nThreads << 1);
        QueryWrapper queryWrapper = getQueryWrapperFromMessage(message);
        //获取总页数
        int total = bOrderDao.selectCount(queryWrapper);
        int pageSize = PageUtil.pageSize;
        // 获取总页数 每页10000条数据
        int totalPageCount= PageUtil.getTotalPageCount(total);
        CountDownLatch countDownLatch = new CountDownLatch(totalPageCount);
        //起始日期
        Date maxDate = null;
        for(int currPageNum = 0;currPageNum < totalPageCount;currPageNum ++){
            //从缓存中取maxDate 如果缓存中存在就从缓存中取，如果不存在就从2000-01-01年开始取
            maxDate = getMaxDateFromRedis() == null ? new Date("2000-01-01") : getMaxDateFromRedis();
            List<BOrder> bOrders = bOrderDao.selectPage(maxDate,pageSize);
            maxDate = bOrders.get(bOrders.size() - 1).getCreateTime();
            //将 maxDate缓存到redis中
            saveMaxDate(maxDate);
            ExportTask exportTask = new ExportTask(bOrders,countDownLatch,currPageNum);
            pool.execute(exportTask);
        }
    }

    protected QueryWrapper getQueryWrapperFromMessage(Message message){
        //从 message的content中获取搜索条件
        return new QueryWrapper();
    }

    protected Date getMaxDateFromRedis(){
        return new Date();
    }



    public void saveMaxDate(Date date){}
}
